package com.example.forum_system.controller;

import com.example.forum_system.common.AppVar;
import com.example.forum_system.common.Result;
import com.example.forum_system.common.ResultCode;
import com.example.forum_system.exception.AppException;
import com.example.forum_system.model.User;
import com.example.forum_system.service.impl.ArticleService;
import com.example.forum_system.service.impl.UserService;
import com.example.forum_system.utils.MD5Utils;
import com.example.forum_system.utils.StringUtil;
import com.example.forum_system.utils.UUIDUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Date;

/**
 * @BelongsProject: 0.forum_system
 * @BelongsPackage: com.example.forum_system.controller
 * @Author : 游在海里的鱼
 * @CreateTime : 2023-11-07  14:23
 * @Version : 1.0
 * @Description : TODO
 */
@Controller
@Slf4j
@RequestMapping("/user")
@RestController
public class UserController {
    @Autowired
    UserService userService;
    @Autowired
    ArticleService articleService;

    @PostMapping("/signUp")
    public Result signUp(User user){
        //1.参数检验
        if(user == null || StringUtil.isEmpty(user.getUsername()) || StringUtil.isEmpty(user.getPassword())){
            log.error(ResultCode.FAILED_PARAMS_VALIDATE.getMessage());
            throw new AppException(Result.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //2.密码加密
        String password = MD5Utils.md5Salt(user.getPassword(), UUIDUtil.UUID_32());
        user.setPassword(password);
        //3.加入数据库
        userService.insertUser(user);
        //4.返回结果给前端
        return Result.success();
    }

    @PostMapping("/signIn")
    public Result signIn(String username, String password, HttpServletRequest request){
        //1.
        if(StringUtil.isEmpty(username) || StringUtil.isEmpty(password)){
            log.error(ResultCode.FAILED_PARAMS_VALIDATE.getMessage());
            throw new AppException(Result.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //2.
        User user = userService.selectByUsername(username);
        if(!MD5Utils.verifyPassword(password,user.getPassword())){
            return Result.failed(ResultCode.FAILED_LOGIN);
        }
        //3.
        HttpSession session = request.getSession(true);
        session.setAttribute(AppVar.SESSION_USER,user);
        //4.
        return Result.success();
    }

    @RequestMapping("/info")
    public Result userInfo(HttpServletRequest request,Long id){
        User user = null;
        //1.未传入用户id时，获取当前登录用户对象
        if(id == null){
            HttpSession session = request.getSession(false);
            user = (User) session.getAttribute(AppVar.SESSION_USER);
        //2.传入用户id时，获取此id的用户对象
        }else {
            if(id < 0){
                log.error("用户id不合法");
                return Result.failed(ResultCode.FAILED_PARAMS_VALIDATE);
            }
            user = userService.selectById(id);
        }
        //3.返回用户对象给前端（已禁止jackson编译密码，状态码）
        return Result.success(user);
    }


    @GetMapping("/logout")
    public Result logout(HttpServletRequest request){
        HttpSession session = request.getSession(false);
        session.invalidate();
        return Result.success();
    }

    @PostMapping("/modifyInfo")
    public Result modifyInfo(HttpServletRequest request,User user){
        if(user == null){
            log.warn("修改用户信息时，传入参数无效");
            return Result.failed(ResultCode.FAILED_PARAMS_VALIDATE);
        }

        HttpSession session = request.getSession(false);
        User srcUser = (User) session.getAttribute(AppVar.SESSION_USER);

        if(!updateUser(srcUser,user)){
            log.warn("修改用户信息时，传入参数无效");
            return Result.failed(ResultCode.FAILED_PARAMS_VALIDATE);
        }
        userService.updateUser(srcUser);
        session.setAttribute(AppVar.SESSION_USER,srcUser);
        return Result.success();
    }

    @PostMapping("/modifyPwd")
    public Result modeifyPassword(HttpServletRequest request,String oldPassword,String newPassword){
        if(StringUtil.isEmpty(oldPassword) || StringUtil.isEmpty(newPassword)){
            log.warn("修改用户密码时，传入参数无效");
            return Result.failed(ResultCode.FAILED_PARAMS_VALIDATE);
        }

        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppVar.SESSION_USER);

        if(!MD5Utils.verifyPassword(oldPassword,user.getPassword())){
            log.warn("修改用户密码时，传入的原密码错误");
            return Result.failed(ResultCode.FAILED_TWO_PWD_NOT_SAME);
        }

        user.setPassword(MD5Utils.md5Salt(newPassword,UUIDUtil.UUID_32()));
        user.setUpdateTime(new Date());

        userService.updateUser(user);
        session.setAttribute(AppVar.SESSION_USER,user);
        return Result.success();
    }

    private boolean updateUser(User srcUser,User user){
        boolean updated = false;
        if(user.getNickname() != null){
            srcUser.setNickname(user.getNickname());
            updated = true;
        }
        if(user.getAvatarUrl() != null){
            srcUser.setAvatarUrl(user.getAvatarUrl());
            updated = true;
        }
        if(user.getEmail() != null){
            srcUser.setEmail(user.getEmail());
            updated = true;
        }
        if(user.getPhoneNum() != null){
            srcUser.setPhoneNum(user.getPhoneNum());
            updated = true;
        }
        if(user.getRemark() != null){
            srcUser.setRemark(user.getRemark());
            updated = true;
        }
        if(updated){
            srcUser.setUpdateTime(new Date());
        }
        return updated;
    }
}
